import React, { useRef, useState, useEffect } from 'react';
import { connect } from 'dva';
import { Tooltip, Card, Button, Modal, message } from 'antd';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import styles from '@/components/common/PateoTable/TableList.less';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { getDicByKey, findDicByCodeSort } from '@/support/common';
import { routerRedux } from 'react-router-dom';
import { PlusOutlined } from '@ant-design/icons';
import CopyButton from '@/components/CopyButton';

const DEFAULT_QUERY = () => ({
  nickname: '',
  phone: '',
  state: '',
  email: '',
  systemType: '',
  speciality: '',
});

const mapStateToProps = (state: any) => ({
  listData: state?.operationTools?.pageData,
  loading: state.loading.effects['operationTools/getFetchPage'],
  dicData: state?.menu?.dicData,
  userProfile: state?.menu?.userProfile,
});

const appPersonnelManagement = props => {
  const {
    dispatch,
    dicData,
    listData,
    loading,
    userProfile,
    location: { pathname = '/' },
  } = props;
  const operator = userProfile.userName;
  const searchRef = useRef(null);
  const [query, setQuery] = useState(DEFAULT_QUERY());
  const { info, confirm } = Modal;

  const specityOptions = findDicByCodeSort(dicData, 'appOperationSpeciality');
  const stateOptions = findDicByCodeSort(dicData, 'appPersonnelState');
  const systemTypeOptions = findDicByCodeSort(dicData, 'appSystemType');
  const pagination = {
    current: 1,
    pageSize: 10,
    total: 0,
    ...(listData?.pagination ?? {}),
  };

  const fetchParams = { type: 'operationTools/getFetchPage', url: '/msuser/devopsuser/page' };
  const refreshList = () => {
    dispatch({
      type: fetchParams.type,
      payload: {
        url: fetchParams.url,
        ...query,
        ...pagination,
      },
    });
  };

  useEffect(() => {
    refreshList();
  }, []);

  const handleUpdatePersonnel = formData => {
    dispatch(
      routerRedux.push({
        pathname: '/operationTools/appPersonnelManagement/appPersonnelDetail',
        state: { isEdit: !!formData, formData },
      }),
    );
  };

  const searchItems = [
    {
      title: '姓名',
      type: 'input',
      key: 'nickname',
    },
    {
      title: '手机号',
      type: 'input',
      key: 'phone',
    },
    {
      title: '状态',
      type: 'select',
      key: 'state',
      selectOptions: stateOptions,
      keyValue: ['dictKey', 'dictValue'],
    },
    {
      title: '邮箱',
      type: 'input',
      key: 'email',
    },
    {
      title: '操作系统',
      type: 'select',
      key: 'systemType',
      selectOptions: systemTypeOptions,
      keyValue: ['dictKey', 'dictValue'],
    },
    {
      title: '使用专业',
      type: 'select',
      key: 'speciality',
      selectOptions: specityOptions,
      keyValue: ['dictKey', 'dictValue'],
    },
  ];

  const longTextRenderConfig = () => {
    return {
      ellipsis: {
        showTitle: false,
      },
      render: value => (
        <Tooltip placement="topLeft" title={value}>
          {value}
        </Tooltip>
      ),
    };
  };

  const columns = [
    {
      title: '姓名',
      width: 140,
      dataIndex: 'nickname',
      fixed: 'left',
      ...longTextRenderConfig()
    },
    {
      title: '手机号',
      width: 120,
      dataIndex: 'phone',
    },
    {
      title: '邮箱',
      width: 150,
      dataIndex: 'email',
      ...longTextRenderConfig()
    },
    {
      title: '使用专业',
      width: 80,
      dataIndex: 'speciality',
      render: (text: any, record: any) => {
        return getDicByKey(dicData, 'appOperationSpeciality', text);
      },
    },
    {
      title: '操作系统',
      width: 100,
      dataIndex: 'systemType',
      render: (text: any, record: any) => {
        return getDicByKey(dicData, 'appSystemType', text);
      },
    },
    {
      title: '设备唯一识别码',
      width: 200,
      dataIndex: 'mobileId',
      ...longTextRenderConfig()
    },
    {
      title: '状态',
      width: 50,
      dataIndex: 'state',
      render: (text: any, record: any) => {
        return getDicByKey(dicData, 'appPersonnelState', text?.toString());
      },
    },
    {
      title: '创建时间',
      width: 180,
      dataIndex: 'createDate',
    },
    {
      title: '创建人',
      width: 140,
      dataIndex: 'createdBy',
    },
    {
      title: '操作',
      width: 200,
      fixed: 'right',
      render: (text: any, record: any) => {
        const btns = [
          {
            title: '编辑',
            key: 'appPersonnelEdit',
            auth: 'appPersonnelManagement_doEdit',
            onConfirm: () => {
              handleUpdatePersonnel(record);
            },
          },
          {
            title: '重置密码',
            // 重置密码（禁用状态下，重置密码按钮置灰）
            disabled: record.state === 1,
            key: 'appPersonnelReset',
            auth: 'appPersonnelManagement_resetPwd',
            onConfirm: () => {
              confirm({
                title: '重置密码',
                icon: false,
                content: `是否确认重置${record.phone}的账号密码`,
                okText: '重置密码',
                onOk() {
                  dispatch({
                    type: 'operationTools/postObj',
                    payload: {
                      url: '/msuser/devopsuser/resetPassword',
                      id: record.id,
                      operator,
                    },
                    callback: res => {
                      const defaultPwd = res?.data?.password ?? '';
                      info({
                        title: '重置密码',
                        icon: false,
                        width: 280,
                        okText: '确认',
                        content: (
                          <div>
                            <p>密码重置成功!</p>
                            <p>手机号: {record.phone}</p>
                            <p>
                              密码: {defaultPwd} <CopyButton value={defaultPwd} />
                            </p>
                          </div>
                        ),
                      });
                    },
                  });
                },
              });
            },
          },
          {
            // 状态：0：启用 1：禁用
            title: record.state ? '启用' : '禁用',
            key: 'appPersonnelEnable',
            auth: 'appPersonnelManagement_enable',
            onConfirm: async () => {
              const isEnabled = record.state === 0;
              const content = isEnabled ? (
                <span>
                  是否确认<span style={{ color: 'orange' }}>禁用</span>账号{record.phone}
                  <br />
                  禁用后将不能在运维工具APP端使用
                </span>
              ) : (
                <span>
                  是否确认<span style={{ color: 'green' }}>启用</span>账号{record.phone}
                  <br />
                  启用后可在运维工具APP端使用
                </span>
              );
              confirm({
                icon: false,
                width: 280,
                content,
                okText: record.state ? '启用' : '禁用',
                onOk() {
                  const url = isEnabled
                    ? '/msuser/devopsuser/disabled'
                    : '/msuser/devopsuser/enabled';
                  dispatch({
                    type: 'operationTools/postObj',
                    payload: {
                      url,
                      id: record.id,
                      operator,
                    },
                    callback: () => {
                      refreshList();
                      message.success('操作成功');
                    },
                  });
                },
              });
            },
          },
        ];
        return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
      },
    },
  ];

  const tableProps = {
    columns: columns, //列表标题信息
    dataSource: listData.list, //要渲染的数据信息
    loading: loading,
    rowKey: record => record.id, //接收每一行信息参数,设置每一行的key
    pagination: {
      ...pagination,
      showSizeChanger: true, //每页显示多少条
      showQuickJumper: true, //输数字快捷跳转
      showTotal: () => {
        return <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>;
      }, //展示页码信息栏
    },
  };

  return (
    <div>
      <Card className={styles.standardTable}>
        <PateoSearchForm
          searchItems={searchItems}
          fetchParams={fetchParams}
          saveFormValues={(val: any) => setQuery(val)}
          handleFormReset={() => setQuery(DEFAULT_QUERY())}
          extraArgs={{
            current: 1,
            pageSize: 10,
          }}
          onRef={e => {
            searchRef.current = e.current;
          }}
        />
      </Card>
      <Card className={styles.standardTable}>
        <Button
          icon={<PlusOutlined />}
          size="small"
          type="primary"
          style={{ marginBottom: '12px' }}
          onClick={() => handleUpdatePersonnel()}
        >
          新增
        </Button>
        <PateoTable
          extraHandle={true}
          tableProps={tableProps}
          fetchParams={fetchParams}
          formValues={query}
          // dispatchFn={this.postAxios}
        />
      </Card>
    </div>
  );
};

export default connect(mapStateToProps)(appPersonnelManagement);
